<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/10/27
 * Time: 14:17
 */

namespace ticket\modules\frontend\controllers;


use ticket\libs\Curl;
use ticket\libs\Tools;
use ticket\modules\frontend\models\OrderInfo;
use ticket\modules\frontend\models\PayConfig;
use yii\base\Exception;
use yii\log\FileTarget;
use yii\web\Controller;
use Yii;

/*** 恐龙园Vip购票，餐饮支付支付回调，通知；
 * Class KlyPayCallbackController
 * @package ticket\modules\frontend\controllers
 */
class KlyPayCallbackController extends Controller
{
    private $sign = '4028A8AB73433F1E0173434469D50014';
    private $key = 'exrVhmRG8dO5WZc8iuCgxqIY0i0RZdFI';   // 支付中心 恐龙园加密kek
    private $dq_key = 'azyIMiuMf3O98K4qIXE3FQyRj4yqpcLA';   // 支付中心 德清加密kek
    private $qzb_key = 'ijgEEtPY31nLov6f1AvLmhrFlQuQzWNS';   // 支付中心 趣周边加密kek
    private $gz_key = 'Van7HWtbWHpLHHMtvS21GjmTlEAQh4Z2';   // 支付中心 新市古镇加密kek
//    private $url = 'https://xxxnk.klygf.com/';
    private $url = 'https://jqxcx.klygf.com/';            // 德清订单支付通知
    private $urlOne = "http://121.236.175.231:8088/";          // 核销优惠券，信易游订单支付通知
    private $urlTwo = "http://218.93.7.157:8082/CaterSystem/inteface/";  // VIP购票，餐饮支付通知



    /*** 恐龙园VIP购票，订单通知
     * @return false|string
     */
    public function actionVipTickets()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $this->recordText(100010,'回调参数-Vip'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
            try{
                $res = $this->checkSign($post,$this->key);
                $this->recordText(22222,'回调参数'.$res,json_encode($post['attach'],JSON_UNESCAPED_UNICODE));
                if ($res and $post['payStatus'] == '00'){
//                    $token = $this->getToken();
//                    if (!$token){
//                        $this->recordText(9999,'获取token失败'.$token,json_encode($post['attach'],JSON_UNESCAPED_UNICODE));
//                    }
                    $url = $this->urlTwo."/imp/payOrdersVip.json";
                    $attachInfo = $post['attach'];
                    if (!empty($attachInfo)){
                        $params = [
                            'orderid' => $attachInfo['oid'],
                            'status' => 1,
                            'token' => '',
                        ];
                        $result = json_decode(Curl::post($url,$params),true);
                        if ($result['code'] != '00'){
                            $this->recordText(9999,'订单通知失败--'.$result['message'],json_encode($params,JSON_UNESCAPED_UNICODE));
                            throw new Exception('订单通知失败--'.$result['message']);
                        }
                        $this->recordText(0,'订单通知成功',json_encode($params,JSON_UNESCAPED_UNICODE));
                        $params = [
                            'relCode' => 0,
                            'msg' => '请求成功',
                        ];
                        return json_encode($params);
                    }
                }
                throw new Exception('签名校验失败--'.$res);
            }catch (Exception $e){
                $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
                return json_encode(['relCode' => 99,'msg' => 'success']);
            }

        }
    }

    /*** 恐龙园餐饮，订单通知
     * @return false|string
     */
    public function actionRestaurant()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $this->recordText(100101,'回调参数-餐饮'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
            try{
                $res = $this->checkSign($post,$this->key);
                if ($res and $post['payStatus'] == '00'){
//                    $token = $this->getToken();
//                    $this->recordText(20002,'token'.$token,json_encode($post,JSON_UNESCAPED_UNICODE));
                    $url = $this->urlTwo."/v2/order/payOrdersV2.json";
                    $attachInfo = $post['attach'];
                    if (!empty($attachInfo['verify'])){  // 优惠券不为空，核销
                        $verifyUrl = $this->urlOne."/ClubMemberSystem/inteface/coupon/verify.json";
                        $paramsVerifyData = [
                            'channel' => $attachInfo['verify']['channel'],
                            'memberId' => $attachInfo['verify']['memberId'],
                            'couponid' => $attachInfo['verify']['couponid'],
                            'couponname' => $attachInfo['verify']['couponname'],
                            'orderId' => $post['payNo'],
                            'sign' => md5($this->sign.date("Ym")),
                        ];
                        $verifyRes = json_decode(Curl::post($verifyUrl,$paramsVerifyData),true);
                        if ($verifyRes['code'] != '00'){  // 核销失败，退款
                            $this->recordText(5555555,'核销优惠券失败--'.json_encode($verifyRes,JSON_UNESCAPED_UNICODE),json_encode($paramsVerifyData,JSON_UNESCAPED_UNICODE));
                            $this->refundMoney($post['payNo'],$attachInfo['totalFee']);
                            throw new Exception('核销优惠券失败');
                        }
                    }
                    $params = [
                        'orderid' => $attachInfo['oid'],
                        'status' => 1,
                        'token' => '',
                    ];
                    $result = json_decode(Curl::post($url,$params),true);
                    if ($result['code'] != '00'){
                        throw new Exception('订单通知失败--'.$result['message']);
                    }
                    $params = [
                        'relCode' => 0,
                        'msg' => '请求成功',
                    ];
                    $this->recordText(0,'通知成功--'.json_encode($verifyRes,JSON_UNESCAPED_UNICODE),json_encode($post,JSON_UNESCAPED_UNICODE));
                    return json_encode($params);
                }
                throw new Exception('签名校验失败--'.$res);
            }catch (Exception $e){
                $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
                return json_encode(['relCode' => 99,'msg' => 'success']);
            }

        }
    }


    
    /**** 恐龙园-信易游订单支付通知
     * @return false|string
     */
    public function actionXyyPayOrders()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $this->recordText(100010,'回调参数-Xyy'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
            try{
                $res = $this->checkSign($post,$this->qzb_key);
                $this->recordText(22222,'回调参数'.$res,json_encode($post['attach'],JSON_UNESCAPED_UNICODE));
                if ($res and $post['payStatus'] == '00'){
                    $url = $this->urlOne."ClubMemberSystem/inteface/xyy/payOrders.json";
                    $attachInfo = $post['attach'];
                    if (!empty($attachInfo)){
                        $params = [
                            'orderid' => $attachInfo['oid'],
                        ];
                        $result = json_decode(Curl::post($url,$params),true);
                        if ($result['code'] != '00'){
                            $this->recordText(9999,'订单通知失败--'.$result['message'],json_encode($params,JSON_UNESCAPED_UNICODE));
                            throw new Exception('订单通知失败--'.$result['message']);
                        }
                        $this->recordText(0,'订单通知成功',json_encode($params,JSON_UNESCAPED_UNICODE));
                        $params = [
                            'relCode' => 0,
                            'msg' => '请求成功',
                        ];
                        return json_encode($params);
                    }
                }
                throw new Exception('签名校验失败--'.$res);
            }catch (Exception $e){
                $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
                return json_encode(['relCode' => 99,'msg' => 'success']);
            }

        }
    }
    
    

    /*** 德清小程序，门票支付
     * @return false|string
     */
    public function actionDqTicket()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $this->recordText(100010,'回调参数-德清门票'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
            try{
                $res = $this->checkSign($post,$this->dq_key);
                $this->recordText(22222,'回调参数'.$res,json_encode($post['attach'],JSON_UNESCAPED_UNICODE));
                if ($res and $post['payStatus'] == '00'){
                    $url = $this->url."/dq_ticket_inter/inteface/routine/payOrders.json";
                    $attachInfo = $post['attach'];
                    if (!empty($attachInfo)){
                        $params = [
                            'orderid' => $attachInfo['oid'],
                            'status' => 1,
                            'noid' => $post['orderSn'],
                        ];
                        $result = json_decode(Curl::post($url,$params),true);
                        if ($result['code'] != '00'){
                            throw new Exception('德清门票通知失败--'.$result['message']);
                        }
                        $this->recordText(0,'德清门票通知成功',json_encode($params,JSON_UNESCAPED_UNICODE));
                        $params = [
                            'relCode' => 0,
                            'msg' => '请求成功',
                        ];
                        return json_encode($params);
                    }
                }
                throw new Exception('签名校验失败--'.$res);
            }catch (Exception $e){
                $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
                return json_encode(['relCode' => 99,'msg' => 'success']);
            }
        }
    }
	
	
	public function actionDqTicketTest()
	{
	    if (Yii::$app->request->isPost){
	        $post = Yii::$app->request->post();
	        $this->recordText(100010,'回调参数-德清门票'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
	        try{
	            $res = $this->checkSign($post,$this->dq_key);
	            $this->recordText(22222,'回调参数'.$res,json_encode($post['attach'],JSON_UNESCAPED_UNICODE));
	            if ($res and $post['payStatus'] == '00'){
	                $url = "https://xxxnk.klygf.com/dq_ticket_inter/inteface/comb/payOrders.json";
	                $attachInfo = $post['attach'];
	                if (!empty($attachInfo)){
	                    $params = [
	                        'orderid' => $attachInfo['oid'],
	                        'status' => 1,
	                        'noid' => $post['orderSn'],
	                    ];
	                    $result = json_decode(Curl::post($url,$params),true);
	                    if ($result['code'] != '00'){
	                        throw new Exception('德清门票通知失败--'.$result['message']);
	                    }
	                    $this->recordText(0,'德清门票通知成功',json_encode($params,JSON_UNESCAPED_UNICODE));
	                    $params = [
	                        'relCode' => 0,
	                        'msg' => '请求成功',
	                    ];
	                    return json_encode($params);
	                }
	            }
	            throw new Exception('签名校验失败--'.$res);
	        }catch (Exception $e){
	            $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
	            return json_encode(['relCode' => 99,'msg' => 'success']);
	        }
	    }
	}

    /*** 德清小程序， 年卡支付通知
     * @return false|string
     */
    public function actionDqYearCard()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $this->recordText(100010,'回调参数-德清年卡'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
            try{
                $res = $this->checkSign($post,$this->dq_key);
                $this->recordText(22222,'回调参数'.$res,json_encode($post['attach'],JSON_UNESCAPED_UNICODE));
                if ($res and $post['payStatus'] == '00'){
                    $url = $this->url."/dq_ticket_inter/inteface/routine/payOrdersYear.json";
                    $attachInfo = $post['attach'];
                    if (!empty($attachInfo)){
                        $params = [
                            'orderid' => $attachInfo['oid'],
                            'status' => 1,
                            'noid' => $post['orderSn'],
                        ];
                        $result = json_decode(Curl::post($url,$params),true);
                        if ($result['code'] != '00'){
                            throw new Exception('德清年卡通知失败--'.$result['message']);
                        }
                        $this->recordText(0,'德清年卡通知成功',json_encode($params,JSON_UNESCAPED_UNICODE));
                        $params = [
                            'relCode' => 0,
                            'msg' => '请求成功',
                        ];
                        return json_encode($params);
                    }
                }
                throw new Exception('签名校验失败--'.$res);
            }catch (Exception $e){
                $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
                return json_encode(['relCode' => 99,'msg' => 'success']);
            }

        }
    }


    /*** 德清小程序, 餐饮支付通知
     * @return false|string
     */
    public function actionDqRestaurant()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $this->recordText(100101,'回调参数-德清餐饮'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
            try{
                $res = $this->checkSign($post,$this->dq_key);
                if ($res and $post['payStatus'] == '00'){
                    $attachInfo = $post['attach'];
                    $url = $this->url."dq_Login/GetOrderdayin?OrderId=".$attachInfo['oid'].'&State=1';
                    if (!empty($attachInfo)){

                        $result = json_decode(Curl::get($url,''),true);
                        if ($result['code'] != '5'){
                            $this->recordText(0,'订单通知失败--'.json_encode($result,JSON_UNESCAPED_UNICODE),json_encode($post,JSON_UNESCAPED_UNICODE));
                            throw new Exception('订单通知失败--'.$result['message']);
                        }
                        $params = [
                            'relCode' => 0,
                            'msg' => '请求成功',
                        ];
                        $this->recordText(0,'通知成功--'.json_encode($result,JSON_UNESCAPED_UNICODE),json_encode($post,JSON_UNESCAPED_UNICODE));
                        return json_encode($params);
                    }
                }
                throw new Exception('签名校验失败--'.$res);
            }catch (Exception $e){
                $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
                return json_encode(['relCode' => 99,'msg' => 'success']);
            }
        }
    }

    /*** 恐龙园门票支付回调接口
     * @return string
     */
    public function actionAliTicketCallback()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $sign = isset($post['sign'])?$post['sign']:'';
            $payData = $payData = $this->getPayConfig(3);
            $key = $payData['key'];
            $postSign = Tools::computeSign($post,$key);
            if ($sign == $postSign){
                if ($post['payStatus'] == '00'){
                    // 修改订单状态
                    $payNo = $post['payNo'];
                    $orderModel = OrderInfo::find()->where('order_number = :osn',[':osn' => $payNo])->one();

                    if (!is_null($orderModel) and $orderModel->order_status != 3){
                        $orderModel->order_status = 3;
                        $orderModel->pay_time = $post['payTime'];
                        $orderModel->pay_number = $post['orderSn'];
                        $orderModel->save(0);
                    }

                    $params = [
                        'relCode' => 0,
                        'msg' => '请求成功',
                    ];

                    //记录佣金
                    if($orderModel->app_id == 1 and $orderModel->share_member_id !=0 ){
                        $url = "https://shop.raysfly.com/api/share-member/add-commission-log";
                        $curl_data = [
                            'appid' =>'SHOP2020wHL09rVh09',
                            'order_id' =>$orderModel->oid,
                            'share_member_id' =>$orderModel->share_member_id,
                            'type' => 1
                        ];
                        $result = Curl::post($url,$curl_data);
                    }


                    return json_encode($params);
                    // 发送智游宝门票
                }
            }
            $this->recordText(99999,'支付回调返回值'.$postSign,json_encode($post));
        }
    }


    /*** 德清小程序，门票支付
     * @return false|string
     */
    public function actionDqTest()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $this->recordText(100010,'回调参数-德清门票'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
            try{
                $res = $this->checkSign($post,$this->dq_key);
                $this->recordText(22222,'回调参数'.$res,json_encode($post['attach'],JSON_UNESCAPED_UNICODE));
                if ($res and $post['payStatus'] == '00'){
                    $url = "http://pdf.chinastock.com.cn/third_gateway/users/sign";
                    $attachInfo = $post['attach'];
                    if (!empty($attachInfo)){
                        $params = [
                            'orderid' => $attachInfo['oid'],
                            'status' => 1,
                            'noid' => $post['orderSn'],
                        ];
                        $result = json_decode(Curl::post($url,$params),true);
                        if ($result['code'] != '00'){
                            throw new Exception('德清门票通知失败--'.$result['message']);
                        }
                        $this->recordText(0,'德清门票通知成功',json_encode($params,JSON_UNESCAPED_UNICODE));
                        $params = [
                            'relCode' => 0,
                            'msg' => '请求成功',
                        ];
                        return json_encode($params);
                    }
                }
                throw new Exception('签名校验失败--'.$res);
            }catch (Exception $e){
                $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
                return json_encode(['relCode' => 99,'msg' => 'success']);
            }

        }
    }


    public function actionGzParking()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $this->recordText(100010,'回调参数-新市古镇停车'.json_encode($post['attach']),json_encode($post,JSON_UNESCAPED_UNICODE));
            try{
                $res = $this->checkSign($post,$this->gz_key);
                $this->recordText(22222,'回调参数'.$res,json_encode($post['attach'],JSON_UNESCAPED_UNICODE));
                if ($res and $post['payStatus'] == '00'){
                    $url = "https://xxxnk.klygf.com/gz_ticket_inter/inteface/invoice/payParkingAt.json";
                    $attachInfo = $post['attach'];
                    if (!empty($attachInfo)){
                        $params = [
                            'parkingNo' => $attachInfo['parkingNo'],
                            'orderId' => $post['payNo'],
                            'openId' => $attachInfo['openId'],
                        ];
                        $result = json_decode(Curl::post($url,$params),true);
                        if ($result['code'] != '00'){
                            throw new Exception('新市古镇停车通知失败--'.$result['message']);
                        }
                        $this->recordText(0,'新市古镇停车通知成功',json_encode($params,JSON_UNESCAPED_UNICODE));
                        $params = [
                            'relCode' => 0,
                            'msg' => '请求成功',
                        ];
                        return json_encode($params);
                    }
                }
                throw new Exception('签名校验失败--'.$res);
            }catch (Exception $e){
                $this->recordText(99999,$e->getMessage(),json_encode($post,JSON_UNESCAPED_UNICODE));
                return json_encode(['relCode' => 99,'msg' => 'success']);
            }

        }

        
    }
    
    
    

    public function actionTest()
    {
        return Tools::showRes('10001','请求成功');
    }
    
    /*** 恐龙园支付回调参数校验
     * @param $data
     * @return bool
     */
    private function checkSign($data,$key)
    {

        $sign = $data['sign'];
        $postSign = Tools::computeSign($data,$key);
        if ($sign == $postSign){
            return true;
        }
        throw new Exception('签名校验失败'.$sign.'--'.$postSign);
    }


    private function getToken()
    {
        $url = $this->url."CaterSystem/inteface/v2/order/getToken.json";
        $result = json_decode(Curl::post($url,[]),true);
        if ($result['code'] == '00'){
            return $result['data']['token'];
        }
        throw new Exception('token获取失败--'.$result['message']);
    }



    protected function recordText($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = \Yii::$app->getRuntimePath() . '/kly_callback/logs_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }

    /*** 获取支付秘钥key
     * @param $appId
     * @return array|null|\yii\db\ActiveRecord
     */
    private function getPayConfig($appId)
    {
        $payConfigModel = new PayConfig();
        $payData = $payConfigModel->getInfo($appId);
        return $payData;
    }

    protected function refundMoney($payUserSerial,$refundFee)
    {
        $paramsRefund = [
            'channelMerId' => 'KLY2020915',
            'appId' => '1',
            'aid' => '1',
            'payUserId' => 'Verify_User',
            'nonceStr' => Tools::createStr(20),
            'timeStamp' => time(),
            'payUserSerial' => $payUserSerial,
            'totalFee' => $refundFee,
            'refundFee' => $refundFee,
            'signType' => 'MD5',
            'refundType' => 'moon',
        ];
        $paramsRefund['sign'] = Tools::computeSign($paramsRefund,$this->key);
        $url = "http://pay.raysfly.com/frontend/wx-pay/refund-order";
        $result = json_decode(Curl::post($url,$paramsRefund),true);
        if ($result['code'] == '0'){
            return true;
        }
        $this->recordText(66666,'退款失败----'.json_encode($result,JSON_UNESCAPED_UNICODE),json_encode($paramsRefund,JSON_UNESCAPED_UNICODE));
    }
    
    
}